import React, { useState } from 'react';
import { 
  LoginForm, 
  ProFormText,
  ProFormSelect,
  ProCard
} from '@ant-design/pro-components';
import { UserOutlined, LockOutlined, IdcardOutlined } from '@ant-design/icons';
import { message, Button, Typography, Space, Steps } from 'antd';
import { history, Link } from 'umi';
import { register } from '@/services/user';

const { Title, Paragraph } = Typography;

/**
 * 注册页面
 */
const RegisterPage: React.FC = () => {
  const [registerError, setRegisterError] = useState<string>('');
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<any>({});

  /**
   * 处理注册表单提交
   * @param values 表单值
   */
  const handleSubmit = async (values: any) => {
    try {
      setSubmitting(true);
      setRegisterError('');
      
      // 确保密码匹配
      if (values.password !== values.confirmPassword) {
        setRegisterError('两次输入的密码不匹配');
        return;
      }
      
      await register({
        englishName: values.englishName,
        chineseName: values.chineseName,
        password: values.password,
        role: 'USER', // 默认注册为普通用户
      });
      
      message.success('注册成功，请登录');
      
      // 跳转到登录页面
      history.push('/');
    } catch (error: any) {
      console.error('注册失败', error);
      setRegisterError(error.message || '注册失败，请稍后重试');
    } finally {
      setSubmitting(false);
    }
  };

  // 手动处理注册按钮点击
  const handleRegisterClick = () => {
    const form = document.querySelector('form');
    if (form) {
      form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center register-bg py-12 px-4 sm:px-6 lg:px-8">
      <div className="w-full max-w-[460px]">
        <div className="text-center mb-10">
          <Title level={2} className="!text-[#1677ff] !m-0">存款AI共建平台</Title>
          <Paragraph className="text-gray-500 mt-2">创建您的专业账号</Paragraph>
        </div>
        
        {registerError && (
          <ProCard className="mb-6 border-l-4 border-l-red-500 bg-red-50" bordered={false}>
            <div className="text-red-600 flex items-center px-2">
              <div>
                <div className="font-medium">注册失败</div>
                <div className="text-sm mt-1">{registerError}</div>
              </div>
            </div>
          </ProCard>
        )}

        <ProCard 
          headerBordered
          title={
            <div className="pt-2">
              <Title level={4} className="!m-0">账号注册</Title>
              <Paragraph type="secondary" className="text-xs mt-1">填写以下信息创建您的账号</Paragraph>
            </div>
          }
        >
          <LoginForm
            formRef={(formRef: any) => {
              if (formRef) {
                formRef.current?.setFieldsValue(formValues);
              }
            }}
            onValuesChange={(changedValues: any) => {
              setFormValues({ ...formValues, ...changedValues });
            }}
            submitter={false}
            onFinish={handleSubmit}
          >

            
            <ProFormText
              name="englishName"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined style={{ color: '#bfbfbf' }} />,
              }}
              placeholder="请输入英文用户名（登录名）"
              rules={[
                {
                  required: true,
                  message: '请输入英文用户名!',
                },
                {
                  min: 4,
                  message: '用户名长度至少为4个字符!',
                },
                {
                  pattern: /^[a-zA-Z0-9_]+$/,
                  message: '用户名只能包含字母、数字和下划线!',
                },
              ]}
            />
            
            <ProFormText
              name="chineseName"
              fieldProps={{
                size: 'large',
                prefix: <IdcardOutlined style={{ color: '#bfbfbf' }} />,
              }}
              placeholder="请输入中文姓名"
              rules={[
                {
                  required: true,
                  message: '请输入中文姓名!',
                },
              ]}
            />
            
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined style={{ color: '#bfbfbf' }} />,
              }}
              placeholder="请输入密码"
              rules={[
                {
                  required: true,
                  message: '请输入密码!',
                },
                {
                  min: 6,
                  message: '密码长度至少为6个字符!',
                },
              ]}
            />
            
            <ProFormText.Password
              name="confirmPassword"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined style={{ color: '#bfbfbf' }} />,
              }}
              placeholder="请再次输入密码"
              rules={[
                {
                  required: true,
                  message: '请确认密码!',
                },
                {
                  min: 6,
                  message: '密码长度至少为6个字符!',
                },
              ]}
            />
            
            <Button 
              type="primary" 
              size="large" 
              block 
              onClick={handleRegisterClick}
              loading={submitting}
              className="mt-6 h-11"
            >
              注册账号
            </Button>
          </LoginForm>
          
          <div className="text-center mt-6 border-t pt-5">
            <Space>
              <span className="text-gray-500">已有账号?</span>
              <Link to="/" className="text-[#1677ff] hover:text-blue-600 font-medium">
                立即登录
              </Link>
            </Space>
          </div>
        </ProCard>
        
        <div className="text-center text-gray-400 text-xs mt-10">
          Copyright © {new Date().getFullYear()} 存款AI共建平台. 保留所有权利。
        </div>
      </div>
    </div>
  );
};

export default RegisterPage; 